package com.qf.filter;

import com.qf.entity.EndUser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//@WebFilter("/*")
public class BlockerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        List<String> urlList = new ArrayList<>();

        urlList.add("loggin.html");
        urlList.add("logOut");
        urlList.add("login");
        urlList.add("captcha");
        urlList.add("meValidate.js");
        urlList.add("commons");
        urlList.add("css");
        urlList.add("fonts");
        urlList.add("img");
        urlList.add("jquery");
        urlList.add("js");
        urlList.add("style.css");
        urlList.add("modernizr-2.8.3.min.js");
        urlList.add("localization");

       // System.out.println(httpRequest.getRequestURL().toString());
        Boolean is = false;
        for (String url: urlList) {
            String requestURL = httpRequest.getRequestURL().toString();
            if (requestURL.contains(url)){
                is = true;
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }

        if (!is){
            //System.out.println(httpRequest.getAttribute("userName"));
            EndUser user = (EndUser) httpRequest.getSession().getAttribute("endUser");
            if (user == null || user.getEndName()==null || user.getEndPassword() == null){
                httpResponse.sendRedirect("loggin.html");
                return;
            }else {
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //这里逻辑错误，不要，二选一  这里如果走else 说明本请求因该是白名单中的啊，上面再放行，下面又重定向乱套了
//        else{
//
//        }


    }

    @Override
    public void destroy() {

    }
}
